﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using UnityEngine;
using Marx;
using ET;
using Marx.EventType;

namespace Demo
{
    [Event]
    public class MarxStartupSuccessHandler : AEvent<MarxStartupSuccess>
    {
        protected override void Run(MarxStartupSuccess a)
        {
            UIManager.Instance.Show(UIStartup.kName);
            GameInitialize().Coroutine();
        }

        private async ETTask GameInitialize()
        {
            await ETTask.CompletedTask;

            if (Global.Instance.ShowAppInfo)
            {
                UIManager.Instance.ShowAppIcon();
            }

#if UNITY_EDITOR
            if (Global.Instance.EnableEditorDLC)
            {
                await DLCHelper.DownloadBundles();
            }
#else
            await DLCHelper.DownloadBundles();
#endif

            LoadCode();
            if(await TimerComponent.Instance.WaitAsync(7000))
            {
                Game.EventSystem.Publish(new Demo.GameStartupFinish());
            }
        }

        private void LoadCode()
        {
            if(Application.isEditor || !Global.Instance.EnableHotfixCode)
            {
                HotfixCodeHelper.LoadCodeDirectly(new string[] { "Hotfix" }, "Hotfix");
            }
            else
            {
                HotfixCodeHelper.LoadCode(Global.Instance.Configs.HotfixCodePath, "Hotfix");
            }
        }
    }

    [Event]
    public class DownloadDLCConfirmHandler : AEvent<Marx.EventType.DownloadConfirm>
    {
        protected override void Run(DownloadConfirm a)
        {
            a.Confirm.Confirm();
        }
    }

    [Event]
    public class GameStartupFinishHandler : AEvent<Demo.GameStartupFinish>
    {
        protected override void Run(GameStartupFinish a)
        {
            var config = Global.Instance.Configs;
            var hotfixEntryClass = HotfixCodeHelper.HotfixEntry.GetTypes().Single(i => i.Name == config.HotfixEntryClass);
            var method = hotfixEntryClass.GetMethod(config.HotfixEntryMethod);
            method.Invoke(null, null);
        }
    }
}
